using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace AopLoadBalancer.Server.DataAccess
{

    public class DalSession : IDisposable
    {
        private SqlConnection connection;
        private SqlTransaction transaction;


        public DalSession(string connectionString)
        {
            connection = new SqlConnection(connectionString);
            connection.Open();
        }

        public void Close()
        {
            connection.Close();
        }

        public SqlCommand CreateCommand(string cmdText)
        {
            if (transaction != null)
            {
                return new SqlCommand(cmdText, connection, transaction);
            }
            else
            {
                return new SqlCommand(cmdText, connection);
            }
        }

        #region Transaction management
        public void BeginTransaction()
        {
            transaction = connection.BeginTransaction();
        }
        public void CommitTransaction()
        {
            EnsureProperTransaction();
            transaction.Commit();
            transaction = null;
        }

        public void RollbackTransaction()
        {
            EnsureProperTransaction();
            transaction.Rollback();
            transaction = null;
        }

        private void EnsureProperTransaction()
        {
            if (transaction == null)
            {
                throw new InvalidOperationException(
                    "Cannot commit transation - current connection is not associated with transaction");
            }
        }
        #endregion

        #region Closing connection
        //TODO - implement disposable
        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (transaction != null)
            {
                transaction.Rollback();
            }


            connection.Close();

        }

        #endregion
    }
}
